package com.leetcode.bit;

/**
 * @author Dennis Li
 * @date 2020/10/27 18:51
 */
public class Divide_29 {

    public int divide(int dividend, int divisor) {
        long ans = 0, up = Math.abs((long) dividend), down = Math.abs((long) divisor);
        if (down > up || up == 0) return 0;
        // 不断进行左移位运算来计数
        while (up >= down) {
            long count = 1, base = down;
            while (up > (base << 1)) {
                count <<= 1;
                base <<= 1;
            }
            ans += count;
            up -= base;
        }
        boolean negative = (dividend ^ divisor) < 0;
        ans = negative ? -ans : ans;
        return (ans > Integer.MAX_VALUE || ans < Integer.MIN_VALUE) ? Integer.MAX_VALUE : (int) ans;
    }

}
